import { create } from "zustand";
import { useEffect } from "react";

// 1.拆分子模块
// 计数相关的子模块
const createCounterStore = (set) => {
  return {
    count: 0,
    inc: () => {
      set((state) => {
        return {
          count: state.count + 1,
        };
      });
    },
  };
};

// 频道列表相关的子模块
const createChannelStore = (set) => {
  return {
    channelList: [],
    getChannelList: async () => {
      // 获取频道列表数据
      const res = await fetch("http://geek.itheima.net/v1_0/channels");
      const jsonRes = await res.json();
      // 调用set方法修改状态数据
      set({
        channelList: jsonRes.data.channels,
      });
    },
  };
};

// 2.组合子模块
const useStore = create((...a) => {
  return {
    ...createCounterStore(...a),
    ...createChannelStore(...a),
  };
});

function App() {
  const { channelList, count, inc, getChannelList } = useStore();
  useEffect(() => {
    // 调用store中的异步获取数据的方法
    getChannelList();
  }, []);
  return (
    <>
      <div>
        {count} <button onClick={inc}>点我加一</button>
      </div>
      <ul>
        {/* 渲染store中的数据 */}
        {channelList.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </>
  );
}

export default App;
